import api from '@api/store_api';
const { img } = require('@utils/imgjson');
import { toast, err, to, scene, get, set } from '@utils/wxapi';
Page({
  data: {
    show: false,
    goodlist: [],
    scrollTops: 0,
    tabCur: 0,
    rightCur: 0,
    item: {},
    goodsCount: 1,
    markNo: 0,
    tabname: {},
    avttab: '',
    avtvalue: [],
    show_top_tab: false,
    sum_count: 0,
    sum_price: 0,
    mchId: '',
    deskId: '',
    popshow: false,
    isclick: true,
    remark: '',
    kou: [
      {
        name: '微辣',
        sel: false,
      },
      {
        name: '中辣',
        sel: false,
      },
      {
        name: '特辣',
        sel: false,
      },
    ],
    kounum: Number,
    pay: [],
    cartshow: false,
    mch: {},
    user: {},
  },
  onLoad(e) {
    if (e.scene) {
      const { mchId, deskId } = scene(e.scene);
      console.log();
      this.setData({ deskId, mchId });
      set('mchId', mchId);
      set('deskId', deskId);
    }
  },
  async onShow() {
    try {
      await this.user();
      await Promise.all([this.goodslist(), this.cartList(), this.get_mch(), this.paylist(), this.zhuo()]);
    } catch (error) {
      err(error);
    }
  },
  async user() {
    try {
      const res = await api.userxx();
      if (res.respCode === 200) {
        const { respCode, source } = await api.getuser();
        if (respCode === 200) {
          const user = JSON.parse(source);
          this.setData({ user });
          set('user', user);
        }
      } else {
        err(res.msg);
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  async get_mch() {
    try {
      const id = get('mchId');
      const { respCode, source } = await api.getmch({ id });
      if (respCode === 200) {
        const mch = JSON.parse(source);
        this.setData({ mch });
        set('mch', mch);
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  async paylist() {
    try {
      const { respCode, source } = await api.payList({ status: 'NORMAL' });
      if (respCode === 200) {
        const list = JSON.parse(source);
        if (list.length > 0 && this.data.isclick) {
          this.setData({
            popshow: true,
            isclick: false,
            pay: list,
          });
        }
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  async zhuo() {
    try {
      const id = get('deskId');
      const { respCode, source } = await api.seated({ id });
      if (respCode === 200) {
        const markNo = JSON.parse(source).markNo;
        set('markNo', markNo);
        this.setData({ markNo });
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  async cartList() {
    try {
      const deskId = get('deskId');
      const { respCode, source } = await api.cartList({ deskId });
      if (respCode === 200) {
        let cart_list = JSON.parse(source);
        cart_list = this.img(cart_list);
        this.setData({ cart_list });
        this.sum(cart_list);
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  img(arr) {
    arr.forEach(e => {
      e.goodsBO.coverUrl = JSON.parse(e.goodsBO.coverUrl);
    });
    return arr;
  },
  sum(arr) {
    try {
      let sum_price = 0;
      let sum_count = 0;
      arr.forEach(e => {
        sum_price += e.goodsBO.price * e.goodsCount;
        sum_count += e.goodsCount;
      });
      sum_price = sum_price.toFixed(2);
      this.setData({
        sum_price,
        sum_count,
      });
    } catch (error) {
      err(error);
      throw error;
    }
  },
  deleted() {
    try {
      const { cart_list } = this.data;
      const id = cart_list.map(e => e.id);
      wx.showModal({
        title: '提示',
        content: '您确定将所有菜品从购物车中移除吗？',
        complete: async res => {
          if (res.confirm) {
            try {
              const { respCode, msg } = await api.eletcai({ id });
              if (respCode === 200) {
                toast('删除成功');
                this.cartList();
              } else {
                toast(msg);
              }
            } catch (error) {
              err(error);
              throw error;
            }
          }
        },
      });
    } catch (error) {
      err(error);
      throw error;
    }
  },
  async goodslist() {
    try {
      const { respCode, source } = await api.dishescla();
      if (respCode === 200) {
        let goodlist = JSON.parse(source);
        goodlist.forEach(e => {
          e.goodsBOList = img(e.goodsBOList);
        });
        console.log(goodlist);
        this.type(goodlist);
        this.setData({ goodlist });
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  type(arr) {
    try {
      let show_top_tab = false;
      let tabname = {};
      arr.forEach(e => {
        const bool = e.name.includes('-');
        if (bool) {
          show_top_tab = true;
        }
        const i = e.name.indexOf('-');
        const name = bool ? e.name.substring(0, i) : e.name;
        const item = bool ? { ...e, name: e.name.split('-').pop() } : e;
        tabname[name] = tabname[name] || [];
        tabname[name].push(item);
      });
      const avttab = Object.keys(tabname)[0];
      const avtvalue = Object.values(tabname)[0] || [];
      if (show_top_tab) {
        this.setData({
          show_top_tab,
          tabname,
          avttab,
          avtvalue,
        });
      } else {
        this.setData({
          show_top_tab,
          avtvalue: arr,
        });
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  navtab(e) {
    const { key, value } = e.currentTarget.dataset;
    this.setData({
      avttab: key,
      avtvalue: value,
      tabCur: 0,
    });
  },
  async sel(e) {
    try {
      if (this.data.user.mobile === '') {
        wx.showModal({
          title: '提示',
          content: '检测到您还未登录，是否前往登录',
          complete: res => {
            if (res.confirm) {
              to('/pages/login/login');
            }
          },
        });
        return;
      }
      const { id } = e.detail;
      this.setData({ show: true });
      const { respCode, source } = await api.Dtlgoods({ id });
      if (respCode === 200) {
        let item = JSON.parse(source);
        item.coverUrl = JSON.parse(item.coverUrl);
        this.setData({ item });
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  onChange(e) {
    this.setData({ goodsCount: e.detail });
  },
  async care() {
    try {
      const { item, goodsCount, kou, remark } = this.data;
      if (!item?.id || !item?.goodsSkuBOList || !goodsCount) {
        throw new Error('添加商品参数不完整，请稍后重试！');
      }
      const skuId = item.goodsSkuBOList[0].id;
      const deskId = get('deskId');
      const selectedKous = kou
        .filter(e => e.sel)
        .map(e => e.name)
        .join('');
      const cartRemark = `${selectedKous}${remark}`;
      const data = {
        goodsId: item.id,
        goodsCount,
        skuId,
        deskId,
        remark: cartRemark,
      };
      const { respCode, msg } = await api.addcaicrt(data);
      if (respCode === 200) {
        this.setData({
          goodsCount: 1,
          show: false,
          item: {},
        });
        toast('添加成功');
      } else {
        toast(msg || '添加失败');
      }
      this.cartList();
    } catch (error) {
      err(error);
      toast('添加商品到购物车失败，请稍后再试！');
      throw error;
    }
  },
  cart_good() {
    this.cartList();
  },
  todtl() {
    to('/user/pages/pay/pay');
  },
  selkou(e) {
    try {
      const { i } = e.currentTarget.dataset;
      const updateKou = this.data.kou.map((item, index) => {
        return {
          ...item,
          sel: index === i ? !item.sel : false,
        };
      });
      this.setData({ kou: updateKou });
    } catch (error) {
      err(error);
      throw error;
    }
  },
  // 切换左边菜单并联动右边
  tabNav(e) {
    let index = e.currentTarget.dataset.index;
    console.log(index);
    this.setData({
      tabCur: index,
      rightCur: index,
      scrollTops: (index - 4) * 50,
    });
  },
  scrollLink(e) {
    const { avtvalue } = this.data;
    const goodlist = [...avtvalue];
    let itemHeight = 0;

    const updateGoodlist = () => {
      return new Promise(resolve => {
        const promises = goodlist.map((item, i) => {
          return new Promise(resolve => {
            const els = wx.createSelectorQuery().select('#scroll-' + i);
            els
              .fields({ size: true }, function (res) {
                item.top = itemHeight;
                itemHeight += res.height;
                item.bottom = itemHeight;
                resolve();
              })
              .exec();
          });
        });
        Promise.all(promises).then(() => {
          resolve();
        });
      });
    };

    const updateDate = () => {
      this.setData({ avtvalue: goodlist });
    };
    const scrollTop = e.detail.scrollTop;
    let selectedTabCur = -1;
    let selectedScrollTops = 0;
    for (let i = 0; i < goodlist.length; i++) {
      if (scrollTop > goodlist[i].top && scrollTop < goodlist[i].bottom) {
        selectedTabCur = i;
        selectedScrollTops = (i - 4) * 50;
        break;
      }
    }
    updateGoodlist().then(() => {
      updateDate();
      if (selectedTabCur !== -1) {
        this.setData({
          tabCur: selectedTabCur,
          scrollTops: selectedScrollTops,
        });
      }
    });
  },
  onclose() {
    this.setData({ show: false });
  },
  onClose() {
    this.setData({ cartshow: false });
  },
  addshow(e) {
    const cartshow = e.detail.data;
    this.setData({ cartshow });
  },
  clone() {
    this.setData({ popshow: false });
  },
  async onPullDownRefresh() {
    await this.user();
    await Promise.all([this.goodslist(), this.zhuo(), this.cartList(), this.get_mch(), this.paylist()]);
  },
});
